package org.geometerplus.android.fbreader.util.rxjava;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * Rxjava封装工具类
 */
public class RxjavaUtil {
    /**
     * 执行Rx通用任务 (IO线程中执行耗时操作 执行完成调用UI线程中的方法)
     */
    public static <T> Disposable executeTask(CommonRxTask<T> t) {
        CommonRxTask.MyOnSubscribe<CommonRxTask<T>> onsubscribe = new CommonRxTask.MyOnSubscribe<CommonRxTask<T>>(t) {
            @Override
            public void subscribe(ObservableEmitter<CommonRxTask<T>> subscriber) {
                getC().doInIOThread();
                subscriber.onNext(getC());
                subscriber.onComplete();
            }
        };
        return Observable.create(onsubscribe)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<CommonRxTask<T>>() {
                    @Override
                    public void accept(CommonRxTask<T> tCommonRxTask) throws Exception {
                        tCommonRxTask.doInUIThread();
                    }
                });
    }
}